package model.dao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import model.dao.ulti.HibernateUtil;
import model.pojo.GioHang;
import org.hibernate.Query;
import org.hibernate.Session;

public class GioHangDAO extends AbstractDAO<GioHang, String> {

    @Override
    protected Class getPOJOClass() {
        return GioHang.class;
    }

    public static String sinhMaGioHang1(Date ndh) {
        String maDonDatHang;
        SimpleDateFormat sdf = new SimpleDateFormat("HHmmssSSSSddMMyyyy");
        String str = sdf.format(ndh);
        maDonDatHang = "GH" + str;
        return maDonDatHang;
    }

    public static String sinhMaGioHang() {
        ArrayList<GioHang> ds;
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "from GioHang s order by s.maGioHang";
        Query query = session.createQuery(hql);
        ds = (ArrayList<GioHang>) query.list();
        session.close();
        String MaCuoi = "";
        if (ds.size() > 0) {
            MaCuoi = ds.get(ds.size() - 1).getMaGioHang();
        } else {
            MaCuoi = "GH000";
        }
        String tam = MaCuoi.substring(2);
        int tam2 = Integer.parseInt(tam);
        tam2++;
        String kq = "GH";
        int n = tam2 / 10 + 1;
        for (int i = 0; i < 3 - n; i++) {
            kq += "0";
        }
        return kq += tam2;
    }

    public static ArrayList<GioHang> timKiem(String maKhachHang) {

        ArrayList<GioHang> ds = new ArrayList<GioHang>();
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "from GioHang s where s.khachHang.maKhachHang=:ma_khach_hang";
        Query query = session.createQuery(hql);
        query.setString("ma_khach_hang", maKhachHang);

        ds = (ArrayList<GioHang>) query.list();
        session.close();
        return ds;
    }

    public static int xoaGioHang(String maGioHang) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        String hql = "delete from ChiTietGioHang where gioHang.maGioHang =:ma_Gio_Hang";
        Query query = session.createQuery(hql);
        query.setString("ma_Gio_Hang", maGioHang);
        int n = query.executeUpdate();
        if (n > 0) {
            hql = "delete from GioHang where maGioHang =:ma_Gio_Hang";
            query = session.createQuery(hql);
            query.setString("ma_Gio_Hang", maGioHang);
            n = query.executeUpdate();
            return n;
        }

        return n;
    }
}
